package com.jshx.sz.gdjt.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.URLSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.jshx.sz.gdjt.R;
import com.jshx.sz.gdjt.activity.listener.MyTextWatcher;
import com.jshx.sz.gdjt.bean.ProjectBean;
import com.jshx.sz.gdjt.constant.ApplicationGlobal;
import com.jshx.sz.gdjt.control.HeaderView;
import com.jshx.sz.gdjt.control.TextEditView;
import com.jshx.sz.gdjt.db.DataBaseUtil;
import com.jshx.sz.gdjt.thread.CommitDataThread;
import com.jshx.sz.gdjt.util.file.UploadMultiFileThread;

/**
 * 任务巡检界面
 * @author caxiang
 * @time 2013-08-20
 */
public class TaskCheckActivity extends SuperActivity 
{
	/**
	 * 任务检查标题栏
	 */
	private HeaderView header;
	
	/**
	 * 安装地址
	 */
	private TextEditView address;
	
	/**
	 * 运行编号
	 */
	private TextEditView runNum;
	
	/**
	 * 温度
	 */
	private TextEditView temperature;
	
	/**
	 * 湿度
	 */
	private TextEditView humidity;

	/**
	 * 互检人
	 */
	private Spinner hujianPerson;
	
	/**
	 * 任务检查项目列表
	 */
	private ListView taskcheck_task_list;
	
	/**
	 * 组件实例化工具
	 */
	private LayoutInflater layoutInflater;
	
	private UploadMultiFileThread uploadMultiThread ;
	/**
	 * 
	 */
	private ArrayList<ProjectBean> data;
	
	/**
	 * 备注
	 */
	private TextEditView taskcheck_remark;
	
	//
	private ArrayList<HashMap<String, String>> userData;
	
	//详情数据
	private HashMap<String, String> detailData;
	
	//
	private String orderNum;
	
	//
	private String type;
	
	String assetCode;
	private Handler imgHandler = new Handler() {        
		@Override
        public void handleMessage(Message msg) {
 
	}};
	
	/**
	 * 页面句柄
	 */
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) 
		{
			int what = msg.what;
			super.handleMessage(msg);
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.taskcheck_activity);
		TAG = "TaskCheckActivity";
		layoutInflater = LayoutInflater.from(this);
		orderNum = getIntent().getStringExtra("orderNo");
		type = getIntent().getStringExtra("type");
		if(type != null && !type.equals("check"))
		assetCode = getIntent().getStringExtra("assetCode");
		if(type != null && !type.equals("check"))
		{
			detailData = DataBaseUtil.queryType1TaskDetail(orderNum);
		}
		if(detailData == null)
		{
			detailData = new HashMap<String, String>();
		}
		detailData.put(DataBaseUtil.task_detail_type1_table_clos[0], orderNum);
		findView();
		initView();
		
		uploadMultiThread=new UploadMultiFileThread(imgHandler);
		uploadMultiThread.start();
	}
	
	/**
	 * 实例化页面组件
	 */
	private void findView() 
	{
		header = (HeaderView)findViewById(R.id.taskcheck_header);
		address = (TextEditView)findViewById(R.id.taskcheck_address);
		runNum = (TextEditView)findViewById(R.id.taskcheck_runnum);
		temperature = (TextEditView)findViewById(R.id.taskcheck_temperature);
		humidity = (TextEditView)findViewById(R.id.taskcheck_humidity);
		hujianPerson = (Spinner)findViewById(R.id.taskcheck_hujianperson);
		taskcheck_task_list = (ListView)findViewById(R.id.taskcheck_task_list);
		taskcheck_remark = (TextEditView)findViewById(R.id.taskcheck_remark);
	}

	/**
	 * 初始化页面数据和页面组件
	 */
	private void initView() 
	{
		header.setTitle("任务检查");
		
		if(type != null && (type.equals("check")|| type.equals("checkHis")))
		{
			header.setTitle("采集-检修记录");
		}
		else
		{
			header.setTitle("审核-检修记录");
		}
		
		
		address.setTitle("安装地址：");
		runNum.setTitle("运行编号：");
		temperature.setTitle("温度：");
		humidity.setTitle("湿度：");
		taskcheck_remark.setTitle("结论：");
		if(type != null && (type.equals("checkHis") || type.equals("examineHis")))
		{
			hujianPerson.setSelected(false);
		}
		//假数据
		if(type != null && type.equals("check"))
		{
			address.setValue("广济路-" + orderNum);
			runNum.setValue("编号NO_30-" + orderNum);
			
		}
		
		header.setLeftButtonClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				TaskCheckActivity.this.finish();
			}
		}, R.drawable.backbtn_select, "返回");
		header.setRightButtonClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				saveData();
				//提交网络
				
				//调用--更新本地手机端 任务列表
				DataBaseUtil dao =new DataBaseUtil();
				dao.updateTaskList(orderNum, type,"1");
				
				 //此处还有一步要提交到服务器
				//调用--数据提交到服务器
				CommitDataThread thread=new CommitDataThread( detailData, type, "1",assetCode);
				thread.start();
				//图片上传
				thread.imgToServer(uploadMultiThread,getImgList());
				
				
				//-------------------------
				TaskCheckActivity.this.finish();
			}
		}, R.drawable.titlebtn_select, "提交");
		setListData();
		taskcheck_task_list.setAdapter(myAdapter);
		taskcheck_task_list.setOnItemClickListener(new OnItemClickListener() 
		{
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				
				Intent intent = new Intent(TaskCheckActivity.this, ProjectDetailActivity.class);
				intent.putParcelableArrayListExtra(ApplicationGlobal.LIST_DATA_FLAG, data);
				intent.putExtra("Index", arg2);
				startActivityForResult(intent, 0);
			}
		});
		
		
		
		//录入数字设置 准备
		DigitsKeyListener numericOnlyListener = new DigitsKeyListener(false,true);
		//上限设置 准备
		
		//设置 数字限制和上限
		temperature.getEdit().setKeyListener(numericOnlyListener);
		MyTextWatcher tm1=new MyTextWatcher(temperature.getEdit());
		temperature.getEdit().addTextChangedListener(tm1);
		
		MyTextWatcher tm2=new MyTextWatcher(humidity.getEdit());
		humidity.getEdit().setKeyListener(numericOnlyListener);
		humidity.getEdit().addTextChangedListener(tm2 );
		
		//二维码扫描到得信息不能修改
		address.getEdit().setEnabled(false);
		runNum.getEdit().setEnabled(false);
		
		setListData();
	}
	
	 
	/**
	 * 获得图片列表
	 * @return
	 */
	private List<String> getImgList()
	{
		List<String> imgNameList=new ArrayList<String>();
		for(int i=0;i<data.size();i++)
		{
			ProjectBean info= data.get(i);
			String cdimg=info.getResualtImagePaths();
			if(cdimg!=null&&!cdimg.equals(""))
			{
				String[] obj=cdimg.split(",");
				for(String temp:obj)
				{
					if(temp!=null&&!temp.equals(""))
					{
						imgNameList.add(temp);
					}
				}
			}
		}
		return imgNameList;
	}

	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == 0 && resultCode == RESULT_OK)
		{
			TaskCheckActivity.this.data = data.getParcelableArrayListExtra(ApplicationGlobal.LIST_DATA_FLAG);
			myAdapter.notifyDataSetChanged();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 设置项目数据
	 */
	private void setListData() {
		data = new ArrayList<ProjectBean>();
		ProjectBean bean1 = new ProjectBean();
		bean1.setProjectName("1.检查各装置指示灯指示状态、液晶显示器状况以及运行情况");
		bean1.setProjectContent("检查通信管理机、通讯服务器、网络交换机、测控装置、杂散电流装置、轨电位模拟量采集器等装置指示灯应指示正常，液晶显示器应显示正常，确认各装置运行正常（主所无测控装置、杂散电流装置、轨电位模拟量采集器，增加检查路由器、MODEM等设备指示灯应指示正常）；");
		data.add(bean1);
		
		ProjectBean bean2 = new ProjectBean();
		bean2.setProjectName("2.ndt650电力监控软件历史及当前告警信息检查");
		bean2.setProjectContent("查看历史事件记录，告警窗口以及遥信告警分画面，确认各设备无异常告警信息。");
		data.add(bean2);
		
		ProjectBean bean3 = new ProjectBean();
		bean3.setProjectName("3.重启通讯管理机A/B机（热启动）");
		bean3.setProjectContent("重启通讯管理机A/B（热启动），并确认重置后装置及软件运行正常");
		data.add(bean3);
		
		ProjectBean bean4 = new ProjectBean();
		bean4.setProjectName("4.ndt650电力监控软件主接线图检查");
		bean4.setProjectContent("查看监视系统主接线图，确认断路器、隔离开关、接地刀闸等设备状态与现场实际位置应一致，确认遥测量正常刷新；");
		data.add(bean4);
		
		ProjectBean bean5 = new ProjectBean();
		bean5.setProjectName("5.SCADA系统通讯状况及SCADA系统与ISCS通讯状态检查");
		bean5.setProjectContent("查看系统网络通信拓扑图，各装置通信状态应正常；pingISCS系统C360装置IP地址，确认SCADA系统与ISCS系统通信通道正常；检查通讯管理机WTX-65U软件，确认各装置通信状态应正常以及SCADA系统与ISCS系统通讯正常；");
		data.add(bean5);
		
		ProjectBean bean6 = new ProjectBean();
		bean6.setProjectName("6.检查通讯管理机GPS对时是否正常");
		bean6.setProjectContent("修改通讯管理机时间，确认GPS对时能正确修正通讯管理机时间；");
		data.add(bean6);
		
		ProjectBean bean7 = new ProjectBean();
		bean7.setProjectName("7.检查音响报警系统");
		bean7.setProjectContent("检查并试验蜂鸣器、警铃良好，并确认投入使用；");
		data.add(bean7);
		
		ProjectBean bean8 = new ProjectBean();
		bean8.setProjectName("8.各选择开关位置状态检查");
		bean8.setProjectContent("所内/调度选择开关应在调度位，上网隔开远方/当地选择开关应在远方位，隔离开关指示灯应正常（主所无上网隔离开关）；");
		data.add(bean8);
		
		ProjectBean bean9 = new ProjectBean();
		bean9.setProjectName("9.KVM、鼠标、键盘、显示器状况检查");
		bean9.setProjectContent("通过键盘Scroll  Lock和Enter键切换，检查鼠标、键盘、显示器使用状态是否能在A/B机之间切换。确认KVM、鼠标、键盘、显示器功能正常；");
		data.add(bean9);
		
		ProjectBean bean10 = new ProjectBean();
		bean10.setProjectName("10.交直流电源空气开关状况检查");
		bean10.setProjectContent("检查控制信号盘各交直流电源空气开关位置应正确；");
		data.add(bean10);
		
		ProjectBean bean11 = new ProjectBean();
		bean11.setProjectName("11.检查屏内温度");
		bean11.setProjectContent("屏内温度宜≤35℃；屏内各设备应无发热或过度热现象，各交、直流开关应无发热现象；");
		data.add(bean11);
		
		ProjectBean bean12 = new ProjectBean();
		bean12.setProjectName("12.检查屏内照明");
		bean12.setProjectContent("与行程开关配合完好，灯泡完好；");
		data.add(bean12);
		
		ProjectBean bean13 = new ProjectBean();
		bean13.setProjectName("13.综合外观检查");
		bean13.setProjectContent("屏内应无异常气味、无异常音响，设备无变形、无破损、无裂纹、无放点痕迹、接线（含通讯电缆及光缆）与卡件无松动、光纤沿线圆滑无拐角；插座无松动，导线无破损，无悬空裸线头，检查显示屏无损伤，无坏点，颜色显示正常；");
		data.add(bean13);
		
		ProjectBean bean14 = new ProjectBean();
		bean14.setProjectName("14.接地检查");
		bean14.setProjectContent("各设备的接地端子（外壳）至铜牌的连接及铜牌的接地均应正常；");
		data.add(bean14);
		
		ProjectBean bean15 = new ProjectBean();
		bean15.setProjectName("15.屏柜外观除尘");
		bean15.setProjectContent("用干净的抹布使用少量酒精，对屏柜外观除尘；");
		data.add(bean15);
		
		ProjectBean bean16 = new ProjectBean();
		bean16.setProjectName("16.检查门磁工作状态");
		bean16.setProjectContent("外观除尘，检查门磁设备工作状态正常；");
		data.add(bean16);
		
		ProjectBean bean17 = new ProjectBean();
		bean17.setProjectName("17.检查模拟盘工作状态");
		bean17.setProjectContent("外观除尘，检查模拟盘设备完好，无损坏，设备状态正确。");
		data.add(bean17);
		
		//数据初始化界面
		dataInitView();
	}

	/**
	 * 检查数据是否合格
	 * @return
	 */
	private boolean checkData()
	{
		return false;
	}
	
	/**
	 * 用数据初始化组件
	 */
	private void dataInitView()
	{
		//本地查询互检人
//		userData = DataBaseUtil.queryCheckUserData(getIntent().getStringExtra("teamId"));
		//本地查询互检人
//		userData = DataBaseUtil.queryCheckUserData(teamId);
		
		try {
			DataBaseUtil dao=new DataBaseUtil();
			userData = dao.getCheckUserData("");
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(detailData.get(DataBaseUtil.task_detail_type1_table_clos[6]) != null)
		{
			taskcheck_remark.setValue(detailData.get(detailData.get(DataBaseUtil.task_detail_type1_table_clos[6])));
		}
		hujianPerson.setAdapter(adapter) ;
		if(detailData == null)
		{
			return;
		}
		if(detailData.get(DataBaseUtil.task_detail_type1_table_clos[2]) != null)
		{
			address.setValue(detailData.get(DataBaseUtil.task_detail_type1_table_clos[2]));
		}
		if(detailData.get(DataBaseUtil.task_detail_type1_table_clos[3]) != null)
		{
			runNum.setValue(detailData.get(DataBaseUtil.task_detail_type1_table_clos[3]));
		}
		if(detailData.get(DataBaseUtil.task_detail_type1_table_clos[4]) != null)
		{
			temperature.setValue(detailData.get(DataBaseUtil.task_detail_type1_table_clos[4]));
		}
		if(detailData.get(DataBaseUtil.task_detail_type1_table_clos[5]) != null)
		{
			humidity.setValue(detailData.get(DataBaseUtil.task_detail_type1_table_clos[5]));
		}
		for(int i = 0; i < data.size(); i++)
		{
			if(detailData.get(DataBaseUtil.task_detail_type1_table_clos[9 + i * 3]) != null)
			{
				data.get(i).setResualt(detailData.get(DataBaseUtil.task_detail_type1_table_clos[9 + i * 3]));
				data.get(i).setHasEdit("true");
			}
			if(detailData.get(DataBaseUtil.task_detail_type1_table_clos[10 + i * 3]) != null)
			{
				data.get(i).setRemark(detailData.get(DataBaseUtil.task_detail_type1_table_clos[10 + i * 3]));
				data.get(i).setHasEdit("true");
			}
			if(detailData.get(DataBaseUtil.task_detail_type1_table_clos[11 + i * 3]) != null)
			{
				data.get(i).setResualtImagePaths(detailData.get(DataBaseUtil.task_detail_type1_table_clos[11 + i * 3]));
				data.get(i).setHasEdit("true");
			}
		}
		if(detailData.get(DataBaseUtil.task_detail_type1_table_clos[8]) != null)
		{
			if(userData != null && userData.size() > 0)
			{
				for (int i = 0; i < userData.size(); i++) {
					if(userData.get(i).get(DataBaseUtil.user_table_clos[0]) != null
							&& userData.get(i).get(DataBaseUtil.user_table_clos[0])
							.equals(detailData.get(DataBaseUtil.task_detail_type1_table_clos[8])))
					{
						hujianPerson.setSelection(i);
						break;
					}
				}
			}
		}
	}
	
	/**
	 * 保存本地数据
	 */
	private void saveData()
	{
		if(detailData == null)
		{
			detailData = new HashMap<String, String>();
		}
		for(int i = 0; i < data.size(); i++)
		{
			detailData.put(DataBaseUtil.task_detail_type1_table_clos[9 + i * 3], data.get(i).getResualt());
			detailData.put(DataBaseUtil.task_detail_type1_table_clos[10 + i * 3], data.get(i).getRemark());
			detailData.put(DataBaseUtil.task_detail_type1_table_clos[11 + i * 3], data.get(i).getResualtImagePaths());
		}
		detailData.put(DataBaseUtil.task_detail_type1_table_clos[0], orderNum);
		detailData.put(DataBaseUtil.task_detail_type1_table_clos[2], address.getEditValue());
		detailData.put(DataBaseUtil.task_detail_type1_table_clos[3], runNum.getEditValue());
		detailData.put(DataBaseUtil.task_detail_type1_table_clos[4], temperature.getEditValue());
		detailData.put(DataBaseUtil.task_detail_type1_table_clos[5], humidity.getEditValue());
		if(userData != null)
		{
			HashMap<String, String> map = userData.get(hujianPerson.getSelectedItemPosition());
			detailData.put(DataBaseUtil.task_detail_type1_table_clos[7], map.get(DataBaseUtil.user_table_clos[1]));
			detailData.put(DataBaseUtil.task_detail_type1_table_clos[8], map.get(DataBaseUtil.user_table_clos[0]));
		}
		DataBaseUtil.updateType1TaskDetail(detailData);
	}
	
	/**
	 * 项目列表适配器
	 */
	private BaseAdapter myAdapter = new BaseAdapter() 
	{
		class ViewHolder{
			ImageView imageLeft;
			ImageView imageRight;
			TextView text;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder;
			if(convertView == null)
			{
				convertView = layoutInflater.inflate(R.layout.project_list_item, null);
				viewHolder = new ViewHolder();
				viewHolder.imageLeft = (ImageView)convertView.findViewById(R.id.project_list_item_leftimage);
				viewHolder.imageRight = (ImageView)convertView.findViewById(R.id.project_list_item_rightimage);
				viewHolder.text = (TextView)convertView.findViewById(R.id.project_list_item_text);
				convertView.setTag(viewHolder);
			}
			else
			{
				viewHolder = (ViewHolder)convertView.getTag();
			}
			if(data.get(position).getHasEdit().equals("false"))
			{
				viewHolder.imageLeft.setBackgroundResource(R.drawable.project_noedit);
			}
			else
			{
				viewHolder.imageLeft.setBackgroundResource(R.drawable.project_hasedit);
			}
			viewHolder.text.setText(data.get(position).getProjectName());
			return convertView;
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public Object getItem(int position) {
			return data.get(position);
		}
		
		@Override
		public int getCount() {
			return data.size();
		}
	};
	
	SpinnerAdapter adapter=new SpinnerAdapter() {
		
		@Override
		public void unregisterDataSetObserver(DataSetObserver observer) {
			
		}
		
		@Override
		public void registerDataSetObserver(DataSetObserver observer) {
			
		}
		
		@Override
		public boolean isEmpty() {
			return false;
		}
		
		@Override
		public boolean hasStableIds() {
			return false;
		}
		
		@Override
		public int getViewTypeCount() {
			return 0;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView text = new TextView(TaskCheckActivity.this);
			text.setTextColor(getResources().getColor(R.color.black));
			text.setPadding(10, 5, 0, 5);
			text.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
			text.setTextSize(20);
			HashMap map = (HashMap)userData.get(position);
            text.setText(map.get(DataBaseUtil.user_table_clos[1]).toString());
            return text;
		}
		
		@Override
		public int getItemViewType(int position) {
			return 0;
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public Object getItem(int position) {
			return userData.get(position);
		}
		
		@Override
		public int getCount() {
			if(userData == null)
			{
				return 0;
			}
			return userData.size();
		}
		
		@Override
		public View getDropDownView(int position, View convertView, ViewGroup parent) {
			TextView text =new TextView(TaskCheckActivity.this);
			text.setTextColor(getResources().getColor(R.color.black));
			text.setPadding(10, 5, 0, 5);
			text.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
			text.setTextSize(20);
			HashMap map=(HashMap)userData.get(position);
            text.setText(map.get(DataBaseUtil.user_table_clos[1]).toString());
            return text;
		}
	};
}
